#include "util.h"
#include <arpa/inet.h>



uint16_t CRC_Check(const uint8_t *CRC_Ptr,uint8_t LEN)
{
    uint16_t CRC_Value = 0;
    uint8_t  i         = 0;
    uint8_t  j         = 0;

    CRC_Value = 0xffff;
    for(i=0;i<LEN;i++)  //LEN为数组长度
    {
        CRC_Value ^= *(CRC_Ptr+i);
        for(j=0;j<8;j++)
        {
            if(CRC_Value & 0x00001)
                CRC_Value = (CRC_Value >> 1) ^ 0xA001;
            else
                CRC_Value = (CRC_Value >> 1);
        }
    }
    CRC_Value = ((CRC_Value >> 8) +  (CRC_Value << 8)); //交换高低字节

    return CRC_Value;
}
std::string unsignedCharToHex(unsigned char c)
{
    const char hexChars[] = "0123456789ABCDEF";
    std::string result;
    result += hexChars[(c >> 4) & 0x0F];  // 高4位
    result += hexChars[c & 0x0F];          // 低4位
    return result;
}



std::string getPeerIP(bufferevent *bev){
    int fd = bufferevent_getfd(bev);
    struct sockaddr_storage ss;
    socklen_t len = sizeof(ss);
    if (getpeername(fd, (struct sockaddr *)&ss, &len) == 0) {
        char ipstr[INET6_ADDRSTRLEN];
        const char *addr;
        if (ss.ss_family == AF_INET) {
            addr = inet_ntop(AF_INET, &(((struct sockaddr_in *)&ss)->sin_addr), ipstr, sizeof(ipstr));
        } else { // AF_INET6
            addr = inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)&ss)->sin6_addr), ipstr, sizeof(ipstr));
        }
        return addr;
    } 

    return "";
}